<?php


	namespace app\services;


	use app\lib\exception\ToastException;

	class QrCodeServices
	{

		const WX_URL = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=%s';

		const UNLIMIT_URL = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s';

		const CREATE_URL = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s';

		private $access_token;

		public function __construct () {
			$this->access_token = AccessTokenServices::getAccessToken();
		}

		//A模式生成永久二维码,数量有限制
		public function getWxaCode ($path) {
			$url = sprintf(self::WX_URL, $this->access_token);
			$ret = postHttps($url, json_encode(['path' => $path]));

			$res = json_decode($ret, true);
			if (is_array($res) && array_key_exists('errcode', $res) && $res['errcode'] != 0) {
				throw new ToastException($res['errmsg'], $res['errcode']);
			}

			$filename = date('YmdHis') . random(6) . '.jpg';
			$dir = public_path() . 'qr/';
			if (!is_dir($dir)) {
				mkdir($dir, 0777, true);
			}
			$file = $dir . $filename;
			file_put_contents(str_replace('\\', '/', $file), $ret);

			return 'qr/' . $filename;
		}

		//B模式,生成永久二维码,数量不限
		public function getWxaCodeUnLimit ($scene, $page) {
			$url = sprintf(self::UNLIMIT_URL, $this->access_token);
			$tmp = postHttps($url, json_encode(['page' => $page, 'scene' => $scene]));

			$ret = json_decode($tmp, true);
			if (is_array($ret) && array_key_exists('errcode', $ret) && $ret['errcode'] != 0) {
				throw new ToastException($ret['errmsg'], $ret['errcode']);
			}
			$filename = date('YmdHis') . random(6) . '.jpg';
			$dir = public_path() . 'qr/';
			if (!is_dir($dir)) {
				mkdir($dir, 0777, true);
			}
			$file = $dir . $filename;
			file_put_contents(str_replace('\\', '/', $file), $tmp);

			return 'qr/' . $filename;
		}

		//C模式,生成永久二维码,数量限制
		public function createWxaCode ($path) {
			$url = sprintf(self::CREATE_URL, $this->access_token);
			$ret = postHttps($url, json_encode(['path' => $path]));

			$res = json_decode($ret, true);
			if (is_array($ret) && array_key_exists('errcode', $res) && $res['errcode'] != 0) {
				throw new ToastException($res['errmsg'], $res['errcode']);
			}

			$filename = date('YmdHis') . random(6) . '.jpg';
			$dir = public_path() . 'qr/';
			if (!is_dir($dir)) {
				mkdir($dir, 0777, true);
			}
			$file = $dir . $filename;
			file_put_contents(str_replace('\\', '/', $file), $ret);

			return 'qr/' . $filename;
		}



        /**
        * 生成老师专属二维码  引入composer require endroid/qr-code
        *
        * @param $id
        *
        * @param
        *
        * @return string
        * @throws
        *
        */
        public function createExclusiveCode ($id) {
            $gz_sid = $this->request->gzSid();

            if ($gz_sid == 0) {


            } else {
                $this->createPng($gz_sid, $id);
            }

            return true;
        }

        /**
        * 生成带连接的二维码
        *
        * @param $gzSid
        * @param $teacherId
        *
        * @param
        *
        * @return bool
        * @throws
        *
        */
        public function createPng ($gzSid, $teacherId) {
            $webUrl = $this->createWebbUrl($gzSid, $teacherId);
            //带url的二维码
            $writer = new PngWriter();
            $qrCode = QrCode::create($webUrl)->setEncoding(new Encoding('UTF-8'))->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())->setSize(300)->setMargin(10)->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())->setForegroundColor(new Color(0, 0, 0))->setBackgroundColor(new Color(255, 255, 255));
            $label = Label::create('')->setTextColor(new Color(0, 0, 255));
            $result = $writer->write($qrCode, null, $label);
            //查询老师信息
            $teacher = FdAdminUser::findOne(['id' => $teacherId], ['id', 'username']);
            $filename = $teacher ? $teacher->username . '.png' : $teacherId . '.png';
            //二维码保存地址
            $dir = Filesystem::getDiskConfig('public', 'root') . '/exclusive_code/' . $gzSid;
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $result->saveToFile($dir . '/' . $filename);

            return true;
        }

        /**
        * 生成url链接
        *
        * @param $gz_sid
        * @param $teacherId
        *
        * @param
        *
        * @return string
        * @throws
        *
        */
        public function createWebbUrl ($gz_sid, $teacherId) {
            $roleType = 2;
            $channelCode = 'h5';
            $studentId = 0;
            $isScan = 2;//通过扫码进入：存在且等于2
            $sign = md5(md5($gz_sid . FdConstant::WEBSITE_SIGN));
            //todo  根据老师ID查询老师所在分组
            $relationId = 0;//老师必须要存在relationId(分组id)

            //生成参数校验
            $check = $this->createCheck($gz_sid, $teacherId, $studentId, $roleType);
            $data = compact('gz_sid', 'roleType', 'channelCode', 'sign', 'studentId', 'teacherId', 'relationId', 'isScan', 'check');
            ksort($data);
            $url = env('FD.FD_URL') . '/H5?chat?' . http_build_query($data);

            return $url;
        }

        /**
        * 生成参数验证的check
        *
        * @param $gzSid
        * @param $teacherId
        * @param $studentId
        * @param $roleType
        *
        * @param
        *
        * @return string
        * @throws
        *
        */
        public function createCheck ($gzSid, $teacherId, $studentId, $roleType) {
            $data = compact('gzSid', 'teacherId', 'studentId', 'roleType');
            ksort($data);
            $str = http_build_query($data);

            return md5($str . '&check=' . FdConstant::URL_PARAMETER_CHECK);
        }

        /**
        * 下载专属二维码
        *
        * @param
        *
        * @return string
        * @throws
        *
        */
        public function downloadExclusiveCode () {
            $gzSid = $this->request->gzSid();
            //要压缩的文件
            $compressedPath = Filesystem::getDiskConfig('public', 'root') . '/exclusive_code/' . $gzSid;
            if (!is_dir($compressedPath)) {
                throw new ToastException('请先生成专属二维码');
            }

            //压缩后的文件名
            $newFile = Filesystem::getDiskConfig('public', 'root') . '/exclusive_code/' . $gzSid . '/' . $gzSid . '.zip';

            $zip = new \ZipArchive();
            if ($zip->open($newFile, \ZipArchive::CREATE) !== true) {
                throw new ToastException('创建zip文件失败');
            }

            //打开文件夹
            $fileList = [];
            $dir = opendir($compressedPath);
            while ($file = readdir($dir)) {
                if ($file != '.' && $file != '..') {
                    $fileList[] = $file;
                    if (is_file($compressedPath . '/' . $file)) {
                        $zip->addFile($compressedPath . '/' . $file, $file);
                    }
                }
            }
            //关闭文件夹
            closedir($dir);
            $zip->close();

            if (empty($fileList)) {
                throw new ToastException('先生成专属二维码');
            }

            //生成的zip文件上传到oss上
            $filename = 'images/' . $gzSid . '/exclusive_code/' . $gzSid . '.zip';
            $aliYun = new  AliYun();
            $aliYun->uploadFile($filename, $newFile);
            //删除本地文件夹
            deleteFolderFile($compressedPath);

            return env('ALIYUN.OSS_CDN_ORIGIN_HOST') . '/' . $filename;
        }
	}
